<!-- V-admin/src/views/analytics/AnalyticsView.vue -->
<template>
  <div class="analytics-container">
    <div class="analytics-header">
      <h1>数据分析</h1>
      <div class="header-actions">
        <el-select v-model="currentPeriod" placeholder="选择时间范围" @change="loadAllData">
          <el-option label="最近7天" value="7d"></el-option>
          <el-option label="最近30天" value="30d"></el-option>
          <el-option label="最近90天" value="90d"></el-option>
          <el-option label="最近1年" value="1y"></el-option>
        </el-select>
        <el-button type="primary" :icon="Refresh" @click="loadAllData">刷新</el-button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 数据概览卡片 -->
    <div v-else>
      <el-row :gutter="20" class="overview-cards">
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="card-content">
              <div class="card-icon users">
                <el-icon><User /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ overviewData.totalUsers || 0 }}</div>
                <div class="card-label">总用户数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="card-content">
              <div class="card-icon activities">
                <el-icon><Calendar /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ overviewData.totalActivities || 0 }}</div>
                <div class="card-label">活动总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="card-content">
              <div class="card-icon products">
                <el-icon><Goods /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">{{ overviewData.totalProducts || 0 }}</div>
                <div class="card-label">商品数量</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="overview-card">
            <div class="card-content">
              <div class="card-icon sales">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="card-info">
                <div class="card-value">¥{{ overviewData.totalSales || 0 }}</div>
                <div class="card-label">
                  总销售额
                  <span class="growth-rate" :class="getGrowthRateClass(overviewData.salesGrowthRate)">
                    {{ overviewData.salesGrowthRate > 0 ? '+' : '' }}{{ overviewData.salesGrowthRate || 0 }}%
                  </span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 销售分析 -->
      <el-card class="chart-card">
        <template #header>
          <span>销售分析</span>
        </template>
        <el-tabs v-model="activeSalesTab">
          <el-tab-pane label="销售趋势" name="trend">
            <div ref="salesTrendChart" class="chart-container"></div>
          </el-tab-pane>
          <el-tab-pane label="商品排行" name="ranking">
            <el-table :data="salesData.productRanking" style="width: 100%">
              <el-table-column prop="product_name" label="商品名称"></el-table-column>
              <el-table-column prop="category" label="分类"></el-table-column>
              <el-table-column prop="sales_count" label="销售次数" width="100"></el-table-column>
              <el-table-column prop="total_quantity" label="销售数量" width="100"></el-table-column>
              <el-table-column prop="total_sales" label="销售额" width="120">
                <template #default="scope">
                  ¥{{ scope.row.total_sales || 0 }}
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="分类销售" name="category">
            <div ref="categorySalesChart" class="chart-container"></div>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 用户行为分析 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>用户增长趋势</span>
            </template>
            <div ref="userGrowthChart" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>用户活跃度分布</span>
            </template>
            <div ref="userActivityChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 活动效果分析 -->
      <el-card class="chart-card">
        <template #header>
          <span>活动效果分析</span>
        </template>
        <el-tabs v-model="activeActivityTab">
          <el-tab-pane label="活动状态分布" name="status">
            <div ref="activityStatusChart" class="chart-container"></div>
          </el-tab-pane>
          <el-tab-pane label="热门活动排行" name="ranking">
            <el-table :data="activityData.popularActivities" style="width: 100%">
              <el-table-column prop="title" label="活动名称"></el-table-column>
              <el-table-column prop="anchor_name" label="主播"></el-table-column>
              <el-table-column prop="registration_count" label="预约人数" width="100"></el-table-column>
              <el-table-column prop="current_participants" label="参与人数" width="100"></el-table-column>
              <el-table-column label="参与率" width="100">
                <template #default="scope">
                  {{ scope.row.participation_rate || 0 }}%
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 订单状态分布 -->
      <el-card class="chart-card">
        <template #header>
          <span>订单状态分布</span>
        </template>
        <div ref="orderStatusChart" class="chart-container"></div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Refresh, 
  User, 
  Calendar, 
  Goods, 
  TrendCharts 
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { adminAPI } from '../../api/admin'

// 响应式数据
const loading = ref(true)
const currentPeriod = ref('30d')
const activeSalesTab = ref('trend')
const activeActivityTab = ref('status')

// 数据存储
const overviewData = ref<any>({})
const salesData = ref<any>({})
const userData = ref<any>({})
const activityData = ref<any>({})

// 图表引用
const salesTrendChart = ref<HTMLElement>()
const categorySalesChart = ref<HTMLElement>()
const userGrowthChart = ref<HTMLElement>()
const userActivityChart = ref<HTMLElement>()
const activityStatusChart = ref<HTMLElement>()
const orderStatusChart = ref<HTMLElement>()

// 图表实例
let salesTrendChartInstance: echarts.ECharts
let categorySalesChartInstance: echarts.ECharts
let userGrowthChartInstance: echarts.ECharts
let userActivityChartInstance: echarts.ECharts
let activityStatusChartInstance: echarts.ECharts
let orderStatusChartInstance: echarts.ECharts

// 增长率样式
const getGrowthRateClass = (rate: number) => {
  if (rate > 0) return 'positive'
  if (rate < 0) return 'negative'
  return 'neutral'
}

// 加载所有数据
const loadAllData = async () => {
  try {
    loading.value = true
    console.log('📊 开始加载数据分析...')

    await Promise.all([
      loadOverviewData(),
      loadSalesData(),
      loadUserData(),
      loadActivityData()
    ])

    // 初始化图表
    await nextTick()
    initCharts()

  } catch (error: any) {
    console.error('❌ 加载数据分析失败:', error)
    ElMessage.error('加载数据失败: ' + (error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 加载概览数据
const loadOverviewData = async () => {
  try {
    const response = await adminAPI.getOverviewAnalytics()
    if (response.success) {
      overviewData.value = response.data
    } else {
      throw new Error(response.message)
    }
  } catch (error) {
    console.error('加载概览数据失败:', error)
    // 使用模拟数据
    overviewData.value = {
      totalUsers: 1560,
      totalActivities: 28,
      totalProducts: 45,
      totalSales: 28900.50,
      salesGrowthRate: 12.5
    }
  }
}

// 加载销售数据
const loadSalesData = async () => {
  try {
    const response = await adminAPI.getSalesAnalytics({ period: currentPeriod.value })
    if (response.success) {
      salesData.value = response.data
    } else {
      throw new Error(response.message)
    }
  } catch (error) {
    console.error('加载销售数据失败:', error)
    // 使用模拟数据
    salesData.value = {
      salesTrend: generateMockSalesTrend(),
      productRanking: generateMockProductRanking(),
      categorySales: generateMockCategorySales(),
      orderStatus: generateMockOrderStatus()
    }
  }
}

// 加载用户数据
const loadUserData = async () => {
  try {
    const response = await adminAPI.getUserAnalytics({ period: currentPeriod.value })
    if (response.success) {
      userData.value = response.data
    } else {
      throw new Error(response.message)
    }
  } catch (error) {
    console.error('加载用户数据失败:', error)
    // 使用模拟数据
    userData.value = {
      userGrowth: generateMockUserGrowth(),
      userActivity: generateMockUserActivity()
    }
  }
}

// 加载活动数据
const loadActivityData = async () => {
  try {
    const response = await adminAPI.getActivityAnalytics({ period: currentPeriod.value })
    if (response.success) {
      activityData.value = response.data
    } else {
      throw new Error(response.message)
    }
  } catch (error) {
    console.error('加载活动数据失败:', error)
    // 使用模拟数据
    activityData.value = {
      activityPerformance: [],
      activityStatus: generateMockActivityStatus(),
      popularActivities: generateMockPopularActivities()
    }
  }
}

// 初始化图表
const initCharts = () => {
  if (salesTrendChart.value) {
    salesTrendChartInstance = echarts.init(salesTrendChart.value)
    renderSalesTrendChart()
  }
  
  if (categorySalesChart.value) {
    categorySalesChartInstance = echarts.init(categorySalesChart.value)
    renderCategorySalesChart()
  }
  
  if (userGrowthChart.value) {
    userGrowthChartInstance = echarts.init(userGrowthChart.value)
    renderUserGrowthChart()
  }
  
  if (userActivityChart.value) {
    userActivityChartInstance = echarts.init(userActivityChart.value)
    renderUserActivityChart()
  }
  
  if (activityStatusChart.value) {
    activityStatusChartInstance = echarts.init(activityStatusChart.value)
    renderActivityStatusChart()
  }
  
  if (orderStatusChart.value) {
    orderStatusChartInstance = echarts.init(orderStatusChart.value)
    renderOrderStatusChart()
  }
}

// 渲染销售趋势图表
const renderSalesTrendChart = () => {
  const trendData = salesData.value.salesTrend || []
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['销售额', '订单数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: trendData.map((item: any) => item.date)
    },
    yAxis: [
      {
        type: 'value',
        name: '销售额',
        position: 'left'
      },
      {
        type: 'value',
        name: '订单数',
        position: 'right'
      }
    ],
    series: [
      {
        name: '销售额',
        type: 'line',
        yAxisIndex: 0,
        data: trendData.map((item: any) => item.daily_sales || 0),
        smooth: true,
        lineStyle: {
          color: '#5470c6'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(84, 112, 198, 0.5)' },
            { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
          ])
        }
      },
      {
        name: '订单数',
        type: 'bar',
        yAxisIndex: 1,
        data: trendData.map((item: any) => item.daily_orders || 0),
        itemStyle: {
          color: '#91cc75'
        }
      }
    ]
  }
  
  salesTrendChartInstance.setOption(option)
}

// 渲染分类销售图表
const renderCategorySalesChart = () => {
  const categoryData = salesData.value.categorySales || []
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [
      {
        name: '分类销售',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: categoryData.map((item: any) => ({
          value: item.total_sales || 0,
          name: item.category || '未分类'
        }))
      }
    ]
  }
  
  categorySalesChartInstance.setOption(option)
}

// 渲染用户增长图表
const renderUserGrowthChart = () => {
  const growthData = userData.value.userGrowth || []
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: growthData.map((item: any) => item.date)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: growthData.map((item: any) => item.daily_new_users || 0),
        type: 'line',
        smooth: true,
        lineStyle: {
          color: '#ee6666'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(238, 102, 102, 0.5)' },
            { offset: 1, color: 'rgba(238, 102, 102, 0.1)' }
          ])
        }
      }
    ]
  }
  
  userGrowthChartInstance.setOption(option)
}

// 渲染用户活跃度图表
const renderUserActivityChart = () => {
  const activityData = userData.value.userActivity || []
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}人 ({d}%)'
    },
    series: [
      {
        name: '用户活跃度',
        type: 'pie',
        radius: '70%',
        data: [
          { value: activityData.find((a: any) => a.activity_level === '高活跃')?.user_count || 0, name: '高活跃', itemStyle: { color: '#67c23a' } },
          { value: activityData.find((a: any) => a.activity_level === '中活跃')?.user_count || 0, name: '中活跃', itemStyle: { color: '#e6a23c' } },
          { value: activityData.find((a: any) => a.activity_level === '低活跃')?.user_count || 0, name: '低活跃', itemStyle: { color: '#f56c6c' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  userActivityChartInstance.setOption(option)
}

// 渲染活动状态图表
const renderActivityStatusChart = () => {
  const statusData = activityData.value.activityStatus || []
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}个 ({d}%)'
    },
    series: [
      {
        name: '活动状态',
        type: 'pie',
        radius: '70%',
        data: statusData.map((item: any) => ({
          value: item.activity_count || 0,
          name: getActivityStatusText(item.status)
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  activityStatusChartInstance.setOption(option)
}

// 渲染订单状态图表
const renderOrderStatusChart = () => {
  const statusData = salesData.value.orderStatus || []
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}单 ({d}%)'
    },
    series: [
      {
        name: '订单状态',
        type: 'pie',
        radius: '70%',
        data: statusData.map((item: any) => ({
          value: item.order_count || 0,
          name: getOrderStatusText(item.status)
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  orderStatusChartInstance.setOption(option)
}

// 状态文本映射
const getActivityStatusText = (status: string) => {
  const statusMap: { [key: string]: string } = {
    'pending': '待审核',
    'published': '已发布',
    'ongoing': '进行中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

const getOrderStatusText = (status: string) => {
  const statusMap: { [key: string]: string } = {
    'pending': '待支付',
    'paid': '已支付',
    'shipped': '已发货',
    'completed': '已完成',
    'cancelled': '已取消',
    'refunded': '已退款'
  }
  return statusMap[status] || status
}

// 模拟数据生成函数（备用）
const generateMockSalesTrend = () => {
  const dates = []
  const today = new Date()
  for (let i = 29; i >= 0; i--) {
    const date = new Date(today)
    date.setDate(date.getDate() - i)
    dates.push({
      date: date.toISOString().split('T')[0],
      daily_sales: Math.floor(Math.random() * 1000) + 500,
      daily_orders: Math.floor(Math.random() * 20) + 5
    })
  }
  return dates
}

const generateMockProductRanking = () => {
  return [
    { product_name: '限定徽章', category: '周边', sales_count: 156, total_quantity: 189, total_sales: 9450 },
    { product_name: '签名照', category: '收藏', sales_count: 89, total_quantity: 89, total_sales: 4450 },
    { product_name: '定制T恤', category: '服装', sales_count: 67, total_quantity: 72, total_sales: 5360 }
  ]
}

const generateMockCategorySales = () => {
  return [
    { category: '周边', total_sales: 12500 },
    { category: '收藏', total_sales: 7800 },
    { category: '服装', total_sales: 5600 }
  ]
}

const generateMockOrderStatus = () => {
  return [
    { status: 'completed', order_count: 156 },
    { status: 'paid', order_count: 45 },
    { status: 'pending', order_count: 23 },
    { status: 'shipped', order_count: 12 }
  ]
}

const generateMockUserGrowth = () => {
  const dates = []
  const today = new Date()
  for (let i = 29; i >= 0; i--) {
    const date = new Date(today)
    date.setDate(date.getDate() - i)
    dates.push({
      date: date.toISOString().split('T')[0],
      daily_new_users: Math.floor(Math.random() * 10) + 1
    })
  }
  return dates
}

const generateMockUserActivity = () => {
  return [
    { activity_level: '高活跃', user_count: 156 },
    { activity_level: '中活跃', user_count: 289 },
    { activity_level: '低活跃', user_count: 845 }
  ]
}

const generateMockActivityStatus = () => {
  return [
    { status: 'published', activity_count: 15 },
    { status: 'completed', activity_count: 8 },
    { status: 'ongoing', activity_count: 3 },
    { status: 'pending', activity_count: 2 }
  ]
}

const generateMockPopularActivities = () => {
  return [
    { title: '夏日音乐会', anchor_name: 'T.七月', registration_count: 156, current_participants: 142, participation_rate: 91 },
    { title: '粉丝见面会', anchor_name: 'T.赵太阳', registration_count: 89, current_participants: 78, participation_rate: 87.6 }
  ]
}

// 组件挂载
onMounted(() => {
  loadAllData()
})

// 组件卸载时销毁图表
import { onUnmounted } from 'vue'
onUnmounted(() => {
  salesTrendChartInstance?.dispose()
  categorySalesChartInstance?.dispose()
  userGrowthChartInstance?.dispose()
  userActivityChartInstance?.dispose()
  activityStatusChartInstance?.dispose()
  orderStatusChartInstance?.dispose()
})
</script>

<style scoped>
.analytics-container {
  padding: 20px;
}

.analytics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  height: 120px;
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.card-icon.users {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-icon.activities {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.card-icon.products {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.card-icon.sales {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.card-label {
  font-size: 14px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 8px;
}

.growth-rate {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
}

.growth-rate.positive {
  background: #f0f9ff;
  color: #409eff;
}

.growth-rate.negative {
  background: #fef0f0;
  color: #f56c6c;
}

.growth-rate.neutral {
  background: #f4f4f5;
  color: #909399;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-container {
  height: 400px;
  width: 100%;
}

.loading-container {
  margin-top: 20px;
}
</style>